import { asyncRouter } from '@/router';
import { Enum } from '@/common/tools/enum';

function filterRouter(asyncRouter:any){
    let accessRoutes:object[];
    accessRoutes = asyncRouter.filter((item:any,index:number)=>{
        return !item?.isAdmin ? item : ''
    })
    return accessRoutes
}

const state = {
    accessRoutes:[],
    addRoutes:[]
}

const mutations = {
    SET_ROUTER(state:any,router:object[]){
        state.accessRoutes = router
    },
    ADD_ROUTER(state:any,router:any){
        if(state.addRoutes.some((route:any)=> route.path === router.path))return;
        state.addRoutes.push(router)
    },
    REMOVE_ROUTER(state:any,path:any){
        if(path === true) return state.addRoutes = [];
        const index = state.addRoutes.findIndex((route:any)=> route.path === path);
        if(index === -1) return;
        state.addRoutes.splice(index,1)
    }
}

const actions = {
    getAuthRouter({ commit }:any,rote:any):any{
        let accessRoutes:object[];
        return new Promise((resolve,reject)=>{
            if(Enum.Authority.ADMIN === rote.userName.toLowerCase()) {
                accessRoutes = asyncRouter;
            } else {
                accessRoutes = filterRouter(asyncRouter);
            }
            commit('SET_ROUTER',accessRoutes)
            resolve(accessRoutes)
        })
    },
    addRouter({ commit }:any,router:any) {
        commit('ADD_ROUTER',router)
    },
    removeRoute({ commit }:any,path:any) {
        commit('REMOVE_ROUTER',path)
    }

}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
